#!/bin/env python
import sqlite
import ConfigParser
import sys
import shutil

def list_user(conn):
    c = conn.cursor()
    c.execute("select user_id,user_login,user_email from user")
    print "Id Name Email"
    for id,login,email in c:
        print id,login,email
    c.close()

def remove_user(conn,id,path):
    c = conn.cursor()
    c.execute("select user_login from user where user_id=%d"%id)
    login = c.fetchone()
    if login:
        if not path.endswith("/"):
            path = path+"/" 
        user_path = path+str(id)
        print "Removing user:%s and files in %s"%(login[0],user_path)
        yes = raw_input("Are you sure?(y/n)")
        if yes != 'y':
            c.close()
            return
        shutil.rmtree(user_path,True)
        c.execute("delete from user where user_id=%d"%id)
        conn.commit()
    else:
        print "Can not find user, Check user id"
    c.close()

if __name__ == "__main__":
    conn = sqlite.connect("../auth.db")
    config = ConfigParser.RawConfigParser()
    config.read("../default.cfg")
    user_dir = config.get('Directories', 'genome_data_folder')
    print "Metaviz User Manager \nUsage:\n"
    print """    List User: ./user.py
    Delete User and remove user files: ./user.py -d user_id\n"""
    print "User Directory is "+user_dir
    if len(sys.argv)==1:
        list_user(conn)
    elif sys.argv[1]=="-d":
        id = int(sys.argv[2])
        print "Deleting id %d"%id
        remove_user(conn,id,user_dir)
    conn.close()

    
    
    



